"use strict";
cc._RF.push(module, '00371cQlglDVIdse39v0U2E', 'GlobalManagerController');
// scripts/GlobalManagerController.ts

"use strict";
// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getGlobalManager = exports.PageType = void 0;
var MeshTools_1 = require("../meshTools/MeshTools");
var Publish_1 = require("../meshTools/tools/Publish");
var EnumBean_1 = require("./bean/EnumBean");
var GlobalBean_1 = require("./bean/GlobalBean");
var LanguageType_1 = require("./bean/LanguageType");
var EventCenter_1 = require("./common/EventCenter");
var GameMgr_1 = require("./common/GameMgr");
var GamePageController_1 = require("./game/GamePageController");
var BlockAnimationManager_1 = require("./game/BlockAnimationManager");
var HallPageController_1 = require("./hall/HallPageController");
var TopUpDialogController_1 = require("./hall/TopUpDialogController");
var ErrorCode_1 = require("./net/ErrorCode");
var GameServerUrl_1 = require("./net/GameServerUrl");
var HttpManager_1 = require("./net/HttpManager");
var MessageBaseBean_1 = require("./net/MessageBaseBean");
var MessageId_1 = require("./net/MessageId");
var WebSocketManager_1 = require("./net/WebSocketManager");
var WebSocketTool_1 = require("./net/WebSocketTool");
var StartUpPageController_1 = require("./start_up/StartUpPageController");
var TipsDialogController_1 = require("./TipsDialogController");
var ToastController_1 = require("./ToastController");
var AudioMgr_1 = require("./util/AudioMgr");
var Config_1 = require("./util/Config");
var AudioManager_1 = require("./util/AudioManager");
var _a = cc._decorator, ccclass = _a.ccclass, property = _a.property;
window.languageName = "en";
var PageType;
(function (PageType) {
    PageType[PageType["START_UP_PAGE"] = 0] = "START_UP_PAGE";
    PageType[PageType["HALL_PAGE"] = 1] = "HALL_PAGE";
    PageType[PageType["GAME_PAGE"] = 2] = "GAME_PAGE";
})(PageType = exports.PageType || (exports.PageType = {}));
var GlobalManagerController = /** @class */ (function (_super) {
    __extends(GlobalManagerController, _super);
    function GlobalManagerController() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.tipsDialogController = null; //这个是错误弹窗 只有一个退出按钮
        _this.topUpDialogController = null; //充值弹窗
        _this.netError = null; //这个是断网的时候展示的转圈的
        _this.toastController = null; //toast 的布局
        _this.startUpPage = null; //启动页
        _this.hallPage = null; //大厅页
        _this.gamePage = null; //游戏页面
        _this.currentPage = PageType.START_UP_PAGE; //当前展示的页面，默认展示的是启动页面
        _this.startUpPageController = null; //启动页面的总管理器
        _this.hallPageController = null; //大厅页面的总管理器
        _this.gamePageController = null; //游戏页面的总管理器
        return _this;
        // update (dt) {}
    }
    GlobalManagerController_1 = GlobalManagerController;
    GlobalManagerController.prototype.onLoad = function () {
        var _this = this;
        // 建立单例引用
        GlobalManagerController_1.Instance = this;
        cc.resources.preloadDir(Config_1.Config.hallRes, cc.SpriteFrame); //提前预加载大厅图片资源
        // 获取音频管理器实例
        var audioMgr = AudioMgr_1.AudioMgr.ins;
        // 初始化音频管理器（如果还未初始化）
        audioMgr.init();
        cc.debug.setDisplayStats(false);
        //获取URL拼接渠道参数
        this.getUrlParams();
        GameMgr_1.GameMgr.H5SDK.AddAPPEvent();
        this.getAppConfig();
        cc.game.on(cc.game.EVENT_SHOW, function () {
            GameMgr_1.GameMgr.Console.Log("EVENT_SHOW");
            GameMgr_1.GameMgr.GameData.GameIsInFront = true;
            // 触发重连
            WebSocketTool_1.WebSocketTool.GetInstance().atOnceReconnect();
            setTimeout(function () {
                AudioManager_1.AudioManager.playBgm();
            }, 200);
        }, this);
        cc.game.on(cc.game.EVENT_HIDE, function () {
            GameMgr_1.GameMgr.Console.Log("EVENT_HIDE");
            GameMgr_1.GameMgr.GameData.GameIsInFront = false;
            // 页面隐藏时立即停止发送帧输入
            if (_this.gamePageController) {
                console.log('[GlobalManagerController] 页面隐藏时立即停止发送帧输入');
                _this.gamePageController.stopFrameInputImmediately();
            }
            // 断开WebSocket连接
            WebSocketTool_1.WebSocketTool.GetInstance().disconnect();
            _this.netError.active = true;
            AudioManager_1.AudioManager.stopBgm();
        }, this);
        //这里监听程序内消息
        GameMgr_1.GameMgr.Event.AddEventListener(EventCenter_1.EventType.AutoMessage, this.onAutoMessage, this);
        //这里监听长链接消息（异常）
        GameMgr_1.GameMgr.Event.AddEventListener(EventCenter_1.EventType.ReceiveErrorMessage, this.onErrorMessage, this);
        //这里监听长链接消息（正常）
        GameMgr_1.GameMgr.Event.AddEventListener(EventCenter_1.EventType.ReceiveMessage, this.onMessage, this);
        this.setCurrentPage(PageType.START_UP_PAGE);
        this.startUpPageController = this.startUpPage.getComponent(StartUpPageController_1.default);
        this.hallPageController = this.hallPage.getComponent(HallPageController_1.default);
        this.gamePageController = this.gamePage.getComponent(GamePageController_1.default);
    };
    /**
     * 根据地图类型设置背景图片（只设置背景，不设置方块皮肤）
     * mapType: 1 -> bg1/bg_up1/bg_down1
     *           2 -> bg2/bg_up2/bg_down2
     */
    GlobalManagerController.prototype.setMapBackground = function (mapType) {
        var suffix = mapType === 2 ? '2' : '1';
        var bgPath = "bg/bg" + suffix;
        var bgUpPath = "bg/bg_up" + suffix;
        var bgDownPath = "bg/bg_down" + suffix;
        // 直接设置背景图片
        this.setBackgroundSprite('game_bg', bgPath);
        this.setBackgroundSprite('bg_up', bgUpPath);
        this.setBackgroundSprite('bg_down', bgDownPath);
    };
    /**
     * 根据地图类型设置方块皮肤（在方块创建后调用）
     * mapType: 1 -> zhuankuai1
     *           2 -> zhuankuai2
     */
    GlobalManagerController.prototype.setBlockSkin = function (mapType) {
        var suffix = mapType === 2 ? '2' : '1';
        var blockSkin = "zhuankuai" + suffix;
        // 切换方块皮肤
        try {
            var mgr = BlockAnimationManager_1.BlockAnimationManager.getInstance();
            if (mgr && typeof mgr.setBlockSkin === 'function') {
                mgr.setBlockSkin(blockSkin);
            }
            else {
                console.warn('BlockAnimationManager 未初始化或 setBlockSkin 方法不存在');
            }
        }
        catch (e) {
            console.warn('切换方块皮肤失败:', e);
        }
    };
    /**
     * 重置时清空背景图片
     */
    GlobalManagerController.prototype.clearMapBackground = function () {
        var _this = this;
        var backgroundNodes = ['game_bg', 'bg_up', 'bg_down'];
        backgroundNodes.forEach(function (nodeName) {
            var root = cc.find('Canvas') || _this.node;
            var node = _this.findNodeByNameDeep(root, nodeName);
            if (node) {
                var sprite = node.getComponent(cc.Sprite);
                if (sprite) {
                    sprite.spriteFrame = null;
                }
            }
        });
    };
    /**
     * 直接设置背景图片（同步方式）
     */
    GlobalManagerController.prototype.setBackgroundSprite = function (nodeName, resPath) {
        var _this = this;
        cc.resources.load(resPath, cc.SpriteFrame, function (err, spriteFrame) {
            if (err) {
                console.warn("\u52A0\u8F7D\u80CC\u666F\u5931\u8D25: " + resPath, err);
                return;
            }
            var root = cc.find('Canvas') || _this.node;
            var node = _this.findNodeByNameDeep(root, nodeName);
            if (!node) {
                console.warn("\u672A\u627E\u5230\u80CC\u666F\u8282\u70B9: " + nodeName);
                return;
            }
            var sprite = node.getComponent(cc.Sprite) || node.addComponent(cc.Sprite);
            sprite.spriteFrame = spriteFrame;
        });
    };
    /**
     * 递归查找节点
     */
    GlobalManagerController.prototype.findNodeByNameDeep = function (root, name) {
        if (!root)
            return null;
        if (root.name === name)
            return root;
        for (var _i = 0, _a = root.children; _i < _a.length; _i++) {
            var child = _a[_i];
            var found = this.findNodeByNameDeep(child, name);
            if (found)
                return found;
        }
        return null;
    };
    GlobalManagerController.prototype.onEnable = function () {
    };
    GlobalManagerController.prototype.onDestroy = function () {
        GameMgr_1.GameMgr.Event.RemoveEventListener(EventCenter_1.EventType.AutoMessage, this.onAutoMessage, this);
        GameMgr_1.GameMgr.Event.RemoveEventListener(EventCenter_1.EventType.ReceiveErrorMessage, this.onErrorMessage, this);
        GameMgr_1.GameMgr.Event.RemoveEventListener(EventCenter_1.EventType.ReceiveMessage, this.onMessage, this);
        // 释放单例引用
        if (GlobalManagerController_1.Instance === this) {
            GlobalManagerController_1.Instance = null;
        }
    };
    GlobalManagerController.prototype.getAppConfig = function () {
        var _this = this;
        GameMgr_1.GameMgr.H5SDK.GetConfig(function (config) {
            var _a, _b, _c;
            MeshTools_1.MeshTools.Publish.appChannel = String(config.appChannel);
            MeshTools_1.MeshTools.Publish.appId = parseInt(config.appId);
            MeshTools_1.MeshTools.Publish.gameMode = String(config.gameMode);
            MeshTools_1.MeshTools.Publish.roomId = (_a = String(config.roomId)) !== null && _a !== void 0 ? _a : "";
            MeshTools_1.MeshTools.Publish.currencyIcon = (_c = (_b = config === null || config === void 0 ? void 0 : config.gameConfig) === null || _b === void 0 ? void 0 : _b.currencyIcon) !== null && _c !== void 0 ? _c : "";
            MeshTools_1.MeshTools.Publish.code = encodeURIComponent(config.code);
            MeshTools_1.MeshTools.Publish.userId = String(config.userId);
            MeshTools_1.MeshTools.Publish.language = String(config.language);
            MeshTools_1.MeshTools.Publish.gsp = config.gsp == undefined ? 101 : parseInt(config.gsp);
            _this.getHpptPath();
        });
    };
    GlobalManagerController.prototype.getHpptPath = function () {
        this.setLanguage(); //先设置语言
        if (!window.navigator.onLine) {
            this.showTips(window.getLocalizedStr('NetworkError'));
        }
        else {
            // 获取游戏服务器地址
            HttpManager_1.HttpManager.Instance.ReqServerUrl(function () {
                var httpUrl = GameServerUrl_1.GameServerUrl.Http;
                var wsUrl = GameServerUrl_1.GameServerUrl.Ws;
                if (httpUrl != "" || wsUrl != "") {
                    WebSocketManager_1.WebSocketManager.GetInstance().connect();
                }
            });
            // GameServerUrl.Ws = "ws://192.168.0.12:2069/acceptor"
            // WebSocketManager.GetInstance().connect();
        }
    };
    GlobalManagerController.prototype.getUrlParams = function () {
        var params = GameMgr_1.GameMgr.Utils.GetUrlParams(window.location.href); //获取当前页面的 url
        if (JSON.stringify(params) != "{}") {
            //@ts-ignore
            if (params.appChannel) {
                //@ts-ignore
                MeshTools_1.MeshTools.Publish.appChannel = params.appChannel;
                if (params.isDataByUrl) {
                    if (params.isDataByUrl === "true") {
                        MeshTools_1.MeshTools.Publish.appId = parseInt(params.appId);
                        MeshTools_1.MeshTools.Publish.gameMode = params.gameMode;
                        MeshTools_1.MeshTools.Publish.userId = params.userId;
                        MeshTools_1.MeshTools.Publish.code = params.code;
                        if (params.language) {
                            MeshTools_1.MeshTools.Publish.language = params.language;
                        }
                        if (params.roomId) {
                            MeshTools_1.MeshTools.Publish.roomId = params.roomId;
                        }
                        if (params.gsp) {
                            MeshTools_1.MeshTools.Publish.gsp = parseInt(params.gsp);
                        }
                        MeshTools_1.MeshTools.Publish.isDataByURL = true;
                    }
                }
            }
        }
    };
    GlobalManagerController.prototype.setLanguage = function () {
        switch (Publish_1.Publish.GetInstance().language) {
            case LanguageType_1.default.SimplifiedChinese: //简体中文
                window.languageName = LanguageType_1.default.SimplifiedChinese_type;
                break;
            case LanguageType_1.default.TraditionalChinese: //繁体中文
                window.languageName = LanguageType_1.default.TraditionalChinese_type;
                break;
            default: //默认是英语
                window.languageName = LanguageType_1.default.English_type;
                break;
        }
        window.refreshAllLocalizedComp();
    };
    GlobalManagerController.prototype.showTips = function (content) {
        this.tipsDialogController.showDialog(content, function () {
            GameMgr_1.GameMgr.H5SDK.CloseWebView();
        });
    };
    //程序内的通知消息
    GlobalManagerController.prototype.onAutoMessage = function (autoMessageBean) {
        switch (autoMessageBean.msgId) {
            case MessageBaseBean_1.AutoMessageId.JumpHallPage: //跳转进大厅页面
                this.setCurrentPage(PageType.HALL_PAGE);
                if (autoMessageBean.data.type === 1) { //1是启动页面跳转的 ，2 是玩家主动离开游戏房间
                    this.hallPageController.LoginSuccess(); //因为初始进来的时候是启动页面，大厅页面是隐藏状态，下面发送的消息收不到，所以需要主动调用一次
                }
                break;
            case MessageBaseBean_1.AutoMessageId.ReconnectionFailureMsg: //长链接重连失败
                this.netError.active = false;
                this.showTips(window.getLocalizedStr('NetworkError'));
                break;
            case MessageBaseBean_1.AutoMessageId.LinkExceptionMsg: //长链接异常
                this.netError.active = true;
                // 断线时立即停止发送帧输入，避免重连前继续发送无效帧
                if (this.gamePageController) {
                    this.gamePageController.stopFrameInputImmediately();
                }
                break;
            case MessageBaseBean_1.AutoMessageId.GameRouteNotFoundMsg: //游戏线路异常的通知
                this.showTips(autoMessageBean.data.code);
                break;
            case MessageBaseBean_1.AutoMessageId.SwitchGameSceneMsg: //切换游戏场景
                this.setCurrentPage(PageType.GAME_PAGE);
                break;
            case MessageBaseBean_1.AutoMessageId.WalletUpdateMsg: //更新金豆余额的通知
                //发送获取更新用户信息的消息
                WebSocketManager_1.WebSocketManager.GetInstance().sendMsg(MessageId_1.MessageId.MsgTypeUserInfo, {});
                break;
            case MessageBaseBean_1.AutoMessageId.ServerCodeUpdateMsg: //更新 code 的通知
                Publish_1.Publish.GetInstance().code = autoMessageBean.data.code;
                break;
        }
    };
    //长链接消息(异常)
    GlobalManagerController.prototype.onErrorMessage = function (messageBean) {
        switch (messageBean.code) {
            case ErrorCode_1.ErrorCode.ErrInvalidInviteCode: //无效的邀请码
                this.hallPageController.joinError();
                break;
            case ErrorCode_1.ErrorCode.ErrRequestUser: //获取用户信息失败
                this.showTips(window.getLocalizedStr('GetUserInfoFailed'));
                // 断开WebSocket连接
                WebSocketTool_1.WebSocketTool.GetInstance().disconnect();
                break;
            case ErrorCode_1.ErrorCode.ErrNotFoundRoom: //没有找到指定的房间
                if (messageBean.msgId != MessageId_1.MessageId.MsgTypeMoveBlock) {
                    this.toastController.showContent(window.getLocalizedStr('RoomDoesNotExist'));
                    //没有找到房间 就直接返回到大厅页面
                    this.setCurrentPage(PageType.HALL_PAGE);
                }
                break;
            case ErrorCode_1.ErrorCode.ErrNotFoundUser: // 没有找到玩家信息
                if (messageBean.msgId === MessageId_1.MessageId.MsgTypeEnterRoom) { //只有在这个messageId下 才会踢出到大厅
                    //没有找到玩家信息 就直接返回到大厅页面
                    this.setCurrentPage(PageType.HALL_PAGE);
                }
                break;
            case ErrorCode_1.ErrorCode.ErrEnoughUser: //房间已满
                this.toastController.showContent(window.getLocalizedStr('RoomIsFull'));
                break;
            case ErrorCode_1.ErrorCode.ErrChangeBalance: //扣除金币失败
            case ErrorCode_1.ErrorCode.ErrNotEnoughCoin: //金币不足
                this.topUpDialogController.show(function () { });
                break;
            case ErrorCode_1.ErrorCode.ErrPlaying: //玩家已经在游戏中了
                //执行一遍 enterroom
                WebSocketManager_1.WebSocketManager.GetInstance().sendMsg(MessageId_1.MessageId.MsgTypeEnterRoom, {}); //重连进来的 玩家请求进入房间
                break;
        }
    };
    //长链接消息(正常)
    GlobalManagerController.prototype.onMessage = function (messageBean) {
        var _this = this;
        switch (messageBean.msgId) {
            case MessageId_1.MessageId.MsgTypeCreateWs: //创建ws连接 成功  
                this.netError.active = false;
                //登录
                WebSocketManager_1.WebSocketManager.GetInstance().sendMsg(MessageId_1.MessageId.MsgTypeLogin, {});
                break;
            case MessageId_1.MessageId.MsgTypeLogin: //获取登录数据并存储
                GlobalBean_1.GlobalBean.GetInstance().loginData = messageBean.data;
                if (this.currentPage === PageType.START_UP_PAGE) {
                    //判断当前是否是在启动页面
                    this.startUpPageController.setLogin();
                }
                else {
                    this.hallPageController.updateGold();
                    this.hallPageController.LoginSuccess();
                    //没有在游戏中，但是还停留在游戏页面
                    if (GlobalBean_1.GlobalBean.GetInstance().loginData.roomId === 0 && this.currentPage === PageType.GAME_PAGE) {
                        this.setCurrentPage(PageType.HALL_PAGE); //返回到大厅
                    }
                }
                break;
            case MessageId_1.MessageId.MsgTypePairRequest: //开始匹配
                this.hallPageController.setHallOrMatch(HallPageController_1.HallOrMatch.MATCH_PARENT);
                this.hallPageController.createMatchView();
                break;
            case MessageId_1.MessageId.MsgTypeCancelPair: //取消匹配
                this.hallPageController.setHallOrMatch(HallPageController_1.HallOrMatch.HALL_PARENT);
                break;
            case MessageId_1.MessageId.MsgTypeGameStart: //游戏开始
                // 检查是否是砖块派对游戏的GameStart消息
                // 原有的NoticeStartGame消息
                var noticeStartGame_1 = messageBean.data;
                GlobalBean_1.GlobalBean.GetInstance().noticeStartGame = noticeStartGame_1; //存储游戏数据
                var index = GlobalBean_1.GlobalBean.GetInstance().noticeStartGame.users.findIndex(function (item) { return item.userId === GlobalBean_1.GlobalBean.GetInstance().loginData.userInfo.userId; }); //搜索 
                //把游戏开始之后最新的金币余额进行赋值
                if (index != -1) {
                    GlobalBean_1.GlobalBean.GetInstance().loginData.userInfo.coin = noticeStartGame_1.users[index].coin;
                }
                // 延迟调用GameStart处理，确保页面已经激活
                this.scheduleOnce(function () {
                    // 根据mapType设置背景图片
                    _this.setMapBackground(noticeStartGame_1.mapType);
                    // 初始化游戏内容
                    if (_this.gamePageController) {
                        _this.gamePageController.handleGameStart();
                        // 倒计时交由帧事件(eventType:1)统一驱动，避免与GameStart重复触发
                    }
                }, 0.1);
                if (noticeStartGame_1.roomType === EnumBean_1.RoomType.RoomTypeCommon) { // 房间类型 1-普通场 2-私人场
                    this.hallPageController.setGameData();
                }
                else {
                    this.setCurrentPage(PageType.GAME_PAGE); //开始游戏进入游戏页面
                }
                break;
            case MessageId_1.MessageId.MsgTypeEnterRoom: //重连的游戏数据
                var enterRoomData_1 = messageBean.data;
                // 如果服务端告知 gameStatus == 6，表示本局已结束：不进行断线重连，直接返回大厅
                if (enterRoomData_1 && enterRoomData_1.gameStatus === 6) {
                    try {
                        // 清理游戏相关全局数据与视觉背景
                        GlobalBean_1.GlobalBean.GetInstance().cleanData && GlobalBean_1.GlobalBean.GetInstance().cleanData();
                        this.clearMapBackground();
                    }
                    catch (e) {
                        console.warn("在处理 gameStatus=6 返回大厅时清理异常:", e);
                    }
                    this.setCurrentPage(PageType.HALL_PAGE);
                    break;
                }
                // 判断是否为断线重连（roomId > 0）
                if (enterRoomData_1 && enterRoomData_1.roomId && enterRoomData_1.roomId > 0) {
                    // 🎯 处理并存储重连数据到GlobalBean（不要提前赋值原始数据，避免使用未处理的坐标）
                    // 同步补充砖块派对的数据，供结算页等模块使用
                    try {
                        var users = enterRoomData_1.users || [];
                        var playerData = users.map(function (u) {
                            // 🎯 处理坐标：如果是(0,0)中心点，转换为NaN让客户端使用保底位置
                            var x = (typeof u.x === 'number') ? u.x : Number.NaN;
                            var y = (typeof u.y === 'number') ? u.y : Number.NaN;
                            // 检测是否为中心点(0,0)，如果是则使用NaN触发保底逻辑
                            var isCenter = !Number.isNaN(x) && !Number.isNaN(y) && Math.abs(x) < 1e-3 && Math.abs(y) < 1e-3;
                            if (isCenter) {
                                console.warn("[EnterRoom] \u68C0\u6D4B\u5230\u4E2D\u5FC3\u70B9\u5750\u6807(0,0)\uFF0C\u8F6C\u6362\u4E3ANaN\u4F7F\u7528\u4FDD\u5E95\u4F4D\u7F6E userId=" + u.userId + ", playerNumber=" + (u.playerNumber || u.pos || 1));
                                x = Number.NaN;
                                y = Number.NaN;
                            }
                            return {
                                userId: u.userId,
                                playerNumber: u.playerNumber || u.pos || 1,
                                // 避免将缺失坐标默认为0（地图中心）。使用 NaN 作为占位，后续由客户端安全回退。
                                x: x,
                                y: y,
                                playerType: u.playerType || 'red',
                                surviveTime: u.surviveTime || 0,
                                rank: u.rank || 0,
                                nickName: u.nickName || u.nick_name || '',
                                avatar: u.avatar || '',
                                coin: typeof u.coin === 'number' ? u.coin : undefined,
                                bpStatus: u.bpStatus
                            };
                        });
                        GlobalBean_1.GlobalBean.GetInstance().noticeStartGame = {
                            roomId: enterRoomData_1.roomId || 0,
                            roomType: enterRoomData_1.roomType || 1,
                            playerNum: enterRoomData_1.playerNum || (Array.isArray(users) ? users.length : 0),
                            mapType: enterRoomData_1.mapType || 1,
                            fee: enterRoomData_1.fee || 0,
                            users: playerData,
                            gameStatus: enterRoomData_1.gameStatus || 1,
                            countDown: enterRoomData_1.countDown || 0,
                        };
                        // 🔍 调试：验证处理后的玩家坐标
                        console.log("[EnterRoom] \u5904\u7406\u540E\u7684\u73A9\u5BB6\u6570\u636E:", playerData.map(function (p) { return ({
                            userId: p.userId,
                            playerNumber: p.playerNumber,
                            x: p.x,
                            y: p.y
                        }); }));
                    }
                    catch (e) {
                        console.warn('断线重连时构建数据失败:', e);
                    }
                    // 跳转到游戏页面
                    this.setCurrentPage(PageType.GAME_PAGE);
                    // 延迟调用断线重连逻辑，确保页面已经切换完成
                    this.scheduleOnce(function () {
                        if (_this.gamePageController) {
                            _this.gamePageController.handleReconnection(enterRoomData_1);
                        }
                        else {
                            console.error("❌ gamePageController未设置，无法处理断线重连");
                        }
                    }, 0.1); // 延迟100ms确保页面切换完成
                }
                else {
                    // 正常的EnterRoom处理（非断线重连）
                    var noticeStartGame2 = enterRoomData_1;
                    GlobalBean_1.GlobalBean.GetInstance().noticeStartGame = noticeStartGame2;
                    this.setCurrentPage(PageType.GAME_PAGE);
                }
                break;
            case MessageId_1.MessageId.MsgTypeLeaveRoom: // 玩家主动离开房间
                var inviteLeve = messageBean.data;
                if (inviteLeve.userId === GlobalBean_1.GlobalBean.GetInstance().loginData.userInfo.userId) {
                    GlobalBean_1.GlobalBean.GetInstance().cleanData(); //清空数据
                    var autoMessageBean = {
                        'msgId': MessageBaseBean_1.AutoMessageId.JumpHallPage,
                        'data': { 'type': 2 } //2 是玩家主动离开游戏房间
                    };
                    GameMgr_1.GameMgr.Event.Send(EventCenter_1.EventType.AutoMessage, autoMessageBean);
                }
                break;
            case MessageId_1.MessageId.MsgTypeCreateInvite: //创建邀请（也就是创建私人游戏房间）
                GlobalBean_1.GlobalBean.GetInstance().inviteInfo = messageBean.data;
                //点击 create 的回调
                this.hallPageController.joinCreateRoom();
                break;
            case MessageId_1.MessageId.MsgTypeAcceptInvite: //接受邀请
                var acceptInvite = messageBean.data;
                GlobalBean_1.GlobalBean.GetInstance().inviteInfo = acceptInvite.inviteInfo;
                this.hallPageController.setAcceptInvite(acceptInvite);
                break;
            case MessageId_1.MessageId.MsgTypeLeaveInvite: //收到离开房间的信息
                var noticeLeaveInvite = messageBean.data;
                this.hallPageController.leaveRoom(noticeLeaveInvite);
                break;
            case MessageId_1.MessageId.MsgTypeInviteReady: //收到有玩家准备的消息
                var noticeUserInviteStatus = messageBean.data;
                this.hallPageController.setReadyState(noticeUserInviteStatus);
                break;
            case MessageId_1.MessageId.MsgTypeNoticeInviteStatus: //广播邀请状态
                var noticeUserInviteStatus2 = messageBean.data;
                this.hallPageController.setReadyState(noticeUserInviteStatus2);
                break;
            case MessageId_1.MessageId.MsgTypeInviteKickOut: //收到玩家被踢出的信息
                var inviteKickOut = messageBean.data;
                if (inviteKickOut.userId === GlobalBean_1.GlobalBean.GetInstance().loginData.userInfo.userId) {
                    this.toastController.showContent(window.getLocalizedStr('kickout1'));
                    //被踢的是自己的话 直接返回大厅
                    this.setCurrentPage(PageType.HALL_PAGE);
                }
                else {
                    //这里拼接一下数据 走离开房间流程，其实是踢出房间
                    var noticeLeaveInvite1 = { 'userId': inviteKickOut.userId, 'isCreator': false };
                    this.hallPageController.leaveRoom(noticeLeaveInvite1);
                }
                break;
            case MessageId_1.MessageId.MsgTypeUserInfo: //更新用户信息的消息
                var userInfo = messageBean.data;
                GlobalBean_1.GlobalBean.GetInstance().loginData.userInfo = userInfo;
                this.hallPageController.updateGold();
                break;
            case MessageId_1.MessageId.MsgTypeSettlement: //大结算
                var noticeSettlement = messageBean.data;
                this.gamePageController.setCongratsDialog(noticeSettlement);
                break;
            case MessageId_1.MessageId.MsgTypeGameFrame: // 游戏帧数据广播
                var gameFrameData = messageBean.data;
                // 将帧数据传递给游戏页面控制器处理
                if (this.gamePageController) {
                    this.gamePageController.handleGameFrame(gameFrameData);
                }
                break;
            // 注意：GameStart消息已在上面统一处理，这里的重复代码已移除
        }
    };
    //设置展示页面的
    GlobalManagerController.prototype.setCurrentPage = function (pageType) {
        this.currentPage = pageType;
        this.startUpPage.active = false;
        this.hallPage.active = false;
        this.gamePage.active = false;
        switch (pageType) {
            case PageType.START_UP_PAGE:
                this.startUpPage.active = true;
                break;
            case PageType.HALL_PAGE:
                this.hallPage.active = true;
                break;
            case PageType.GAME_PAGE:
                this.gamePage.active = true;
                break;
        }
    };
    var GlobalManagerController_1;
    // 全局单例，便于其他脚本安全获取
    GlobalManagerController.Instance = null;
    __decorate([
        property(TipsDialogController_1.default)
    ], GlobalManagerController.prototype, "tipsDialogController", void 0);
    __decorate([
        property(TopUpDialogController_1.default)
    ], GlobalManagerController.prototype, "topUpDialogController", void 0);
    __decorate([
        property(cc.Node)
    ], GlobalManagerController.prototype, "netError", void 0);
    __decorate([
        property(ToastController_1.default)
    ], GlobalManagerController.prototype, "toastController", void 0);
    __decorate([
        property(cc.Node)
    ], GlobalManagerController.prototype, "startUpPage", void 0);
    __decorate([
        property(cc.Node)
    ], GlobalManagerController.prototype, "hallPage", void 0);
    __decorate([
        property(cc.Node)
    ], GlobalManagerController.prototype, "gamePage", void 0);
    GlobalManagerController = GlobalManagerController_1 = __decorate([
        ccclass
    ], GlobalManagerController);
    return GlobalManagerController;
}(cc.Component));
exports.default = GlobalManagerController;
// 提供便捷的静态获取方法
function getGlobalManager() {
    if (GlobalManagerController.Instance)
        return GlobalManagerController.Instance;
    // 兜底：尝试从场景中查找（Canvas 优先）
    var canvas = cc.find('Canvas');
    if (canvas) {
        var comp = canvas.getComponentInChildren('GlobalManagerController');
        if (comp) {
            GlobalManagerController.Instance = comp;
            return comp;
        }
    }
    var scene = cc.director.getScene();
    if (scene) {
        for (var _i = 0, _a = scene.children; _i < _a.length; _i++) {
            var node = _a[_i];
            var comp = node.getComponent('GlobalManagerController');
            if (comp) {
                GlobalManagerController.Instance = comp;
                return comp;
            }
        }
    }
    return null;
}
exports.getGlobalManager = getGlobalManager;
if (!CC_EDITOR) {
    cc.Sprite.prototype["onLoad"] = function () {
        this.srcBlendFactor = cc.macro.BlendFactor.ONE;
        this.dstBlendFactor = cc.macro.BlendFactor.ONE_MINUS_SRC_ALPHA;
        // 确保 spriteFrame 和其纹理存在
        if (this.spriteFrame && this.spriteFrame.getTexture()) {
            this.spriteFrame.getTexture().setPremultiplyAlpha(true);
        }
        else {
            console.warn("SpriteFrame or Texture is null");
        }
    };
    cc.Label.prototype["onLoad"] = function () {
        this.srcBlendFactor = cc.macro.BlendFactor.ONE;
        this.dstBlendFactor = cc.macro.BlendFactor.ONE_MINUS_SRC_ALPHA;
    };
    cc.macro.ALLOW_IMAGE_BITMAP = false; // 禁用 Bitmap 图片格式
}

cc._RF.pop();